<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 扁平结构转为树状结构 -->
    <script>
      function convertToTree(flatData) {
        let treeData = []
        let map = new Map()
        let outputObj, pid
        for (let i = 0; i < flatData.length; i++) {
          pid = flatData[i].pid
          if (map.has(pid)) {
            if (!map.get(pid).childrens) map.get(pid).childrens = []
            let obj = new Object(flatData[i])
            map.get(pid).childrens.push(obj)
            map.set(flatData[i].id, obj)
          } else if (!map.has(pid) && pid == 0) {
            outputObj = new Object(flatData[i])
            treeData.push(outputObj)
            map.set(flatData[i].id, outputObj)
          }
        }
        return treeData
      }
      console.log(
        convertToTree([
          {
            id: '01',
            pid: '',
            name: '老王',
            children: []
          },
          {
            id: '02',
            pid: '01',
            name: '小张',
            children: []
          },
          {
            id: '03',
            pid: '02',
            name: '小xx',
            children: []
          }
        ])
      )
    </script>
  </body>
</html>
